package com.yunhuajinfu.fragment;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okhttputils.model.HttpParams;
import com.yunhuajinfu.R;
import com.yunhuajinfu.activity.TouZiDetailsActivity;
import com.yunhuajinfu.base.LazyFragment;
import com.yunhuajinfu.entity.BaoLiInfo;
import com.yunhuajinfu.http.HttpCallBack;
import com.yunhuajinfu.http.HttpUtils;
import com.yunhuajinfu.mian.Config;
import com.yunhuajinfu.nbpullToRefresh.BaseRefreshListener;
import com.yunhuajinfu.nbpullToRefresh.PullToRefreshLayout;
import com.yunhuajinfu.response.BaoLiRes;
import com.yunhuajinfu.response.BorrowCountRes;
import com.yunhuajinfu.tool.Tool;
import com.yunhuajinfu.view.CircleProgressView;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by ekikousei易皇星 on 16/11/16.
 * E-mail:13764664731@163.com
 * Signature:缘分是本书,翻的不经意会错过,读的太认真会流泪!!
 * <p/>
 * TODO:类描述:  信用贷
 */
public class XinyongFragment extends LazyFragment implements BaseRefreshListener {
    TextView tv_money_number;    //累计投资金额
    TextView tv_people_number;   //累计投资人数
    ListView mlistview;
    private PullToRefreshLayout mPullToRefreshLayout;
    //
    private View view;
    BaoLiAdapter baoLiAdapter;

    private int pageNum = 1;
    private int numPerPage = 10;
    private boolean flag = true;
    ArrayList<BaoLiInfo> page = new ArrayList<>();
    //
    private   BorrowCountRes res;

    @Override
    public View initView() {
        LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);                    //第一个参数布局文件
        view = inflater.inflate(R.layout.fragment_baoli, null);
        tv_money_number = (TextView) view.findViewById(R.id.tv_money_number);
        tv_people_number = (TextView) view.findViewById(R.id.tv_people_number);
        mlistview = (ListView) view.findViewById(R.id.listview);
        mPullToRefreshLayout= (PullToRefreshLayout) view.findViewById(R.id.mPullToRefreshLayout);
        //
        mPullToRefreshLayout.setRefreshListener(this);
        baoLiAdapter = new BaoLiAdapter(page, getActivity());
        mlistview.setAdapter(baoLiAdapter);
        if(null!=res){
            setmBorrowCountRes(res);
        }

        return view;
    }


    @Override
    public void initData() {

    }

    @Override
    public void firstVisiblegetData() {

            getBaoliData(pageNum, numPerPage);
            getnumber();


    }

    /**
     * 获取宝理列表数据
     */
    private void getBaoliData(int pageNum, int numPerPage) {
        HttpParams params = new HttpParams();
        params.put("pageNum", pageNum + "");
        params.put("numPerPage", numPerPage + "");
        params.put("borrowTypeCode", "BL");

        HttpUtils.post(Config.BORROW_LIST, params, new HttpCallBack(getActivity(), "加载中...") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {

                if (null != result) {
                    try {
                        BaoLiRes res = new BaoLiRes(new JSONObject(result.toString()));

                        if (flag == true) {
                            mPullToRefreshLayout.finishRefresh();
                            if(res.getPage().size()>0){
                                page.clear();
                                page = res.getPage();
                            }else {
                                page.clear();
                                Toast.makeText(getActivity(), "无数据", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            mPullToRefreshLayout.finishLoadMore();
                            if (!res.getCurrentPage().equals(res.getTotalPage())) {
                                page.addAll(res.getPage());
                            } else {
                                if (res.getPage().size() > 0) {
                                    page.addAll(res.getPage());
                                } else {
                                    Toast.makeText(getActivity(), "无更多加载数据", Toast.LENGTH_SHORT).show();
                                }
                            }
                        }

                        //
                        baoLiAdapter.UpdateAdapter(page);


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }


            }


            @Override
            public void onError(String code, String message) {
                mPullToRefreshLayout.finishRefresh();
                mPullToRefreshLayout.finishLoadMore();

                Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
            }
        });


    }

    @Override
    public void refresh() {
        flag = true;
        pageNum = 1;
        getBaoliData(pageNum, numPerPage);

        getnumber();
    }

    @Override
    public void loadMore() {

        flag = false;
        pageNum++;
        getBaoliData(pageNum, numPerPage);
    }


    public class BaoLiAdapter extends BaseAdapter {

        private List<BaoLiInfo> list;
        private Context context;
        LayoutInflater inflater;

        private LiJiTouZiClickListener mliJiTouZiClickListener;

        public BaoLiAdapter(List<BaoLiInfo> list, Context context) {
            this.list = list;
            this.context = context;
            inflater = LayoutInflater.from(context);
            mliJiTouZiClickListener = new LiJiTouZiClickListener();
        }

        public void UpdateAdapter(List<BaoLiInfo> list) {
            this.list = list;
            notifyDataSetChanged();
        }


        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            StringBuffer sb = new StringBuffer();
            ViewHolder viewHolder = null;
            if (viewHolder == null) {
                viewHolder = new ViewHolder();

                convertView = inflater.inflate(R.layout.baoli_item, null);


                viewHolder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
                viewHolder.tv_shouyi = (TextView) convertView.findViewById(R.id.tv_shouyi);
                viewHolder.tv_day = (TextView) convertView.findViewById(R.id.tv_day);
                viewHolder.tv_isDay = (TextView) convertView.findViewById(R.id.tv_isDay);
                viewHolder.mCircleProgressView = (CircleProgressView) convertView.findViewById(R.id.mCircleProgressView);
                viewHolder.tv_touzi = (TextView) convertView.findViewById(R.id.tv_touzi);
                viewHolder.tv_borrowTags01 = (TextView) convertView.findViewById(R.id.tv_borrowTags01);
                //
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();

            }

            BaoLiInfo info = list.get(position);
            String number = info.getTenderSum();   // 以容金额
            String sum = info.getBorrowSum();   //总金额
            //设置进度
            viewHolder.mCircleProgressView.setProgress(StringValueOfInt(number, sum));
            //设置文本
            viewHolder.mCircleProgressView.setProgressText(StringValueOf(number, sum)+"%");
            viewHolder.tv_name.setText(info.getBorrowTitle());
            viewHolder.tv_shouyi.setText(info.getAnnualInterestRate() + "%");
            //加息算法
//            if (info.getInterestGrowth().equals("0.00")) {
//                viewHolder.tv_shouyi.setText(subZeroAndDot(info.getAnnualInterestRate())+"%");
//            } else {
//                viewHolder.tv_shouyi.setText(subZeroAndDot(StringValuesjian(info.getAnnualInterestRate().toString().trim(), info.getInterestGrowth().toString().trim())) + "% +" + subZeroAndDot(info.getInterestGrowth().toString().trim())+"%");
//
//            }
            viewHolder.tv_day.setText(info.getBorrowTimeLimit());
            //
            if (info.getIsDay().equals("1")) {
                viewHolder.tv_isDay.setText("天");
            } else {
                viewHolder.tv_isDay.setText("个月");
            }

            if (null != info.getBorrowTags() || !info.getBorrowTags().equals("")) {

                String[] split = info.getBorrowTags().split(",");
                for (int i = 0; i < split.length; i++) {
                    sb.append(split[i] + " ");
                }
                viewHolder.tv_borrowTags01.setText(sb.toString().trim());
            }

            if (info.getPublished().equals("2")) {
                if (info.getBorrowStatus().equals("6")) {
                    if (Tool.compare_date(info.getAllowTenderTime())) {
                        viewHolder.tv_touzi.setText("立即投资");
                    } else {
                        viewHolder.tv_touzi.setText("筹募期已结束");
                    }
                } else if (info.getBorrowStatus().equals("8") || info.getBorrowStatus().equals("11") || info.getBorrowStatus().equals("12")) {

                    viewHolder.tv_touzi.setText(getbiaoType(info.getBorrowStatus()));
                } else {
                    //贷加入
                }

            } else if (info.getPublished().equals("1")) {

                viewHolder.tv_touzi.setText(" 即将发布");
            }


            //事件监听
            viewHolder.tv_touzi.setOnClickListener(mliJiTouZiClickListener);
            viewHolder.tv_touzi.setTag(list.get(position));
            return convertView;
        }


        public final class ViewHolder {

            TextView tv_shouyi;
            TextView tv_day;
            CircleProgressView mCircleProgressView;
            TextView tv_touzi;
            TextView tv_name;
            TextView tv_isDay;
            TextView tv_borrowTags01;


        }

        /**
         * 立即投资事件监听
         */
        class LiJiTouZiClickListener implements View.OnClickListener {

            @Override
            public void onClick(View v) {

                BaoLiInfo info = (BaoLiInfo) v.getTag();
                Intent intent = new Intent(context, TouZiDetailsActivity.class);
                intent.putExtra("mBaoLiInfo", info);
                intent.putExtra("type", "2000");
                startActivityForResult(intent, 2000);
            }
        }

        /**
         * Stirng 转int
         *
         * @param currentnumber
         * @param sum
         * @return
         */

        public float StringValueOfInt(String currentnumber, String sum) {
            float floatstr = 0.f;
            float m = Float.valueOf(currentnumber);
            float mm = Float.valueOf(sum);
            DecimalFormat fnum = new DecimalFormat("##0.00");
            floatstr = (float) ((m / (int) mm) * 100);
            BigDecimal b = new BigDecimal(floatstr);
            float f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
            //   b.setScale(2,  BigDecimal.ROUND_HALF_UP) 表明四舍五入，保留两位小数
            return f1;
        }

        public String  StringValueOf(String currentnumber, String sum) {
            float floatstr = 0.f;
            float m = Float.valueOf(currentnumber);
            float mm = Float.valueOf(sum);
            floatstr = (float) ((m / (int) mm) * 100);
            DecimalFormat fnum = new DecimalFormat("##0.00");
            return fnum.format(floatstr);
        }


        public String getbiaoType(String type) {
            if (type.equals("8")) {
                return "满标";
            }
            if (type.equals("11")) {
                return "还款中";
            }
            if (type.equals("12")) {
                return "还款完成";
            }
            return "";

        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 2000) {
            getBaoliData(pageNum, numPerPage);
        }
    }


    public  void getnumber(){

        /**
         *
         * 获取投资统计
         */
        HttpParams params=new HttpParams();
        HttpUtils.post(Config.BORROWCOUNT, params, new HttpCallBack(getActivity(),"加载中...") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {

                if(null!=result){

                    try {
                        res=new BorrowCountRes(new JSONObject(result.toString()));
                        setmBorrowCountRes(res);


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }

            @Override
            public void onError(String code, String message) {
                mPullToRefreshLayout.finishRefresh();
                mPullToRefreshLayout.finishLoadMore();

                Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
            }
        });

    }

    public void setmBorrowCountRes(BorrowCountRes mBorrowCountRes) {
        if (null != mBorrowCountRes) {
            tv_money_number.setText("累计投资金额(元):" + mBorrowCountRes.getTenderSum());
            tv_people_number.setText("累计投资人数(位):" + mBorrowCountRes.getTenderCount());
        }

    }


    /**
     *
     * @param num
     * @param min
     * @return  String转float相减
     */
    public String StringValuesjian(String num, String min) {
        float floatnum = Float.parseFloat(num);
        float floatmin = Float.parseFloat(min);
        float values = floatnum - floatmin;
        try {
            return String.format("%.2f", values);
        } catch (Exception e) {

            return "0.00";
        }

    }
    /**
     * 使用java正则表达式去掉多余的.与0
     * @param s
     * @return
     */
    public static String subZeroAndDot(String s){
        if(s.indexOf(".") > 0){
            s = s.replaceAll("0+?$", "");//去掉多余的0
            s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
        }
        return s;
    }

}
